#!/usr/bin/env python
# coding=utf-8

"""
Join records of two files.
For example:
file1:
A	1	2
B	4	3

file2:
B	b
A	a

CrossJoin.py file1 file2 file3
then 
file3:
A	1	2	|	A	a
B	4	3	|	B	b

"""

import os
import sys
import codecs
import string
import logging

# set log
logFileName = 'CrossJoin.log'
def init_log():
    logger = logging.getLogger()
    hdlr = logging.FileHandler(logFileName)
    formatter = logging.Formatter('%(asctime)s %(levelname)s:: %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.INFO)
    return logger

log = init_log()


class RepeatedRecordError(Exception):pass

def cross_join(list1, list2):
	'list1 and list2 may be changed in the function.\n'
	for pos1 in range(len(list1)):
		cnt = len(filter(lambda x:x[0]==list1[pos1][0], list2))
		if  cnt > 1:
			raise RepeatedRecordError()
		for pos2 in range(len(list2)):
			if list1[pos1][0] == list2[pos2][0]:
				list1[pos1] += [u'\t|\t']
				list1[pos1] += list2[pos2]
				list2.pop(pos2)
				break
	return list1, list2

def read_list(filename):
	f = codecs.open(filename, 'r', 'utf-8')
	ret = []
	for line in f.readlines():
		while line[-1].isspace():
			line = line[:-1]
		ret.append(list(line.split('\t')))
	return ret

def main():
	if len(sys.argv) != 4:
		print(r'Usage:')
		print(r'CrossJoin.py file1 file2 outfile')
		sys.exit(0)
	file1 = sys.argv[1]
	file2 = sys.argv[2]
	outfile = sys.argv[3]
	list1 = read_list(file1)
	list2 = read_list(file2)
	(list1, list2) = cross_join(list1, list2)
	outf = codecs.open(outfile, 'w', 'utf-8')
	for r in list1:
		outf.write(string.join(r, u'\t') + u'\n')
	outf.write('\n\n\nRest Records in %s : \n\n' % (file2,))
	for r in list2:
		outf.write(string.join(r, u'\t') + u'\n')


if __name__ == '__main__':
	main()
